package com.hy.frame.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.hy.frame.util.AutoUtil;
import com.hy.frame.widget.ui.R;

import java.lang.ref.WeakReference;

public class DesignHelper {

    protected WeakReference<View> mTarget;
    protected BackgroundStyle background;
    /**
     * 设计尺寸
     */
    protected int designScreenWidth;
    /**
     * 设计比例缩放比例
     */
    protected float designScale = 1F;
    public boolean scaleEnabled;
    protected int width;
    protected int height;

    public DesignHelper(@NonNull View target) {
        mTarget = new WeakReference<>(target);
    }

    private Context getContext() {
        if (mTarget == null || mTarget.get() == null) return null;
        View v = mTarget.get();
        return v.getContext();
    }

    public void loadAttributes(AttributeSet attrs, int defStyleAttr) {
        if (mTarget == null || mTarget.get() == null) return;
        View v = mTarget.get();
        Context context = v.getContext();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IDesignAuto, defStyleAttr, 0);
        this.designScreenWidth = a.getDimensionPixelSize(R.styleable.IDesignAuto_designScreenWidth, AutoUtil.getDesignScreenWidth(context));
        this.scaleEnabled = a.getBoolean(R.styleable.IDesignAuto_designScaleEnabled, true);
        this.designScale = calDesignScale();
        int padding = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPadding, 0);
        int paddingLeft = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingLeft, padding);
        int paddingStart = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingStart, 0);
        int paddingTop = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingTop, padding);
        int paddingRight = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingRight, padding);
        int paddingEnd = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingEnd, 0);
        int paddingBottom = a.getDimensionPixelSize(R.styleable.IDesignAuto_designPaddingBottom, padding);
        a.recycle();
        if (v.getMinimumWidth() > 0){
            v.setMinimumWidth(calDesignSize(v.getMinimumWidth()));
        }
        if (v.getMinimumHeight() > 0){
            v.setMinimumHeight(calDesignSize(v.getMinimumHeight()));
        }
        if (paddingLeft > 0)
            paddingLeft = calDesignSize(paddingLeft);
        else
            paddingLeft = v.getPaddingLeft();
        if (paddingStart > 0)
            paddingStart = calDesignSize(paddingStart);
        if (paddingTop > 0)
            paddingTop = calDesignSize(paddingTop);
        else
            paddingTop = v.getPaddingTop();
        if (paddingRight > 0)
            paddingRight = calDesignSize(paddingRight);
        else
            paddingRight = v.getPaddingRight();
        if (paddingEnd > 0)
            paddingEnd = calDesignSize(paddingEnd);
        if (paddingBottom > 0)
            paddingBottom = calDesignSize(paddingBottom);
        else
            paddingBottom = v.getPaddingBottom();
        if (paddingStart > 0 || paddingEnd > 0) {
            v.setPaddingRelative(paddingStart, paddingTop, paddingEnd, paddingBottom);
        } else {
            v.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        }
    }

    public void loadBackgroundAttributes(AttributeSet attrs, int defStyleAttr) {
        if (mTarget == null || mTarget.get() == null) return;
        View v = mTarget.get();
        Context context = v.getContext();
        background = new BackgroundStyle();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IDesignBackground, defStyleAttr, 0);
        background.backgroundColor = a.getColor(R.styleable.IDesignBackground_designBackgroundColor, Color.TRANSPARENT);
        background.circle = a.getBoolean(R.styleable.IDesignBackground_designCircle, false);
        background.radius = calDesignSize(a.getDimensionPixelSize(R.styleable.IDesignBackground_designRadius, 0));
        background.leftTop = calDesignSize(a.getDimensionPixelSize(R.styleable.IDesignBackground_designRadiusLeftTop, 0));
        background.rightTop = calDesignSize(a.getDimensionPixelSize(R.styleable.IDesignBackground_designRadiusRightTop, 0));
        background.leftBottom = calDesignSize(a.getDimensionPixelSize(R.styleable.IDesignBackground_designRadiusLeftBottom, 0));
        background.rightBottom = calDesignSize(a.getDimensionPixelSize(R.styleable.IDesignBackground_designRadiusRightBottom, 0));
        background.alphaStart = a.getFloat(R.styleable.IDesignBackground_designAlphaStart, 0f);
        if (background.alphaStart < 0 || background.alphaStart > 1) background.alphaStart = 1f;
        background.alphaEnd = a.getFloat(R.styleable.IDesignBackground_designAlphaEnd, 0f);
        if (background.alphaEnd < 0 || background.alphaEnd > 1) background.alphaEnd = 1f;
        background.angle = a.getInt(R.styleable.IDesignBackground_designAngle, 0);
        if (background.angle < -360) background.angle = -360;
        else if (background.angle > 360) background.angle = 360;
        a.recycle();
        updateBackgroundDrawable();
    }

    /**
     * 背景颜色
     */
    public void setBackgroundColor(int backgroundColor) {
        if (background == null) return;
        if (background.backgroundColor == backgroundColor) return;
        background.backgroundColor = backgroundColor;
        updateBackgroundDrawable();
    }

    public BackgroundStyle getBackground() {
        return background;
    }

    private void updateBackgroundDrawable() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            return;
        }
        if (mTarget == null || mTarget.get() == null) return;
        if (background == null) return;
        if (background.backgroundColor == Color.TRANSPARENT) return;
        //重建Drawable
        //QMUIRoundButtonDrawable a;
        //GradientDrawable
        GradientDrawable draw = new GradientDrawable();
        draw.setShape(GradientDrawable.RECTANGLE);
        if (background.alphaStart == background.alphaEnd) {//纯色
            if (background.alphaStart > 0)
                draw.setColor(getColorWithAlpha(background.alphaStart, background.backgroundColor));
            else
                draw.setColor(background.backgroundColor);
        } else { //渐变
            draw.setGradientType(GradientDrawable.LINEAR_GRADIENT);

            draw.setColors(new int[]{getColorWithAlpha(background.alphaStart, background.backgroundColor), getColorWithAlpha(background.alphaEnd, background.backgroundColor)});//增加渐变效果需要使用setColors方法来设置颜色（中间可以增加多个颜色值）

            //方向
            GradientDrawable.Orientation orientation = GradientDrawable.Orientation.LEFT_RIGHT;
            switch (background.angle) {
                case 0:
                    orientation = GradientDrawable.Orientation.LEFT_RIGHT;
                    break;
                case 45:
                    orientation = GradientDrawable.Orientation.BL_TR;
                    break;
                case 90:
                    orientation = GradientDrawable.Orientation.BOTTOM_TOP;
                    break;
                case 135:
                    orientation = GradientDrawable.Orientation.BR_TL;
                    break;
                case 180:
                    orientation = GradientDrawable.Orientation.RIGHT_LEFT;
                    break;
                case 225:
                    orientation = GradientDrawable.Orientation.TR_BL;
                    break;
                case 270:
                    orientation = GradientDrawable.Orientation.TOP_BOTTOM;
                    break;
                case 315:
                    orientation = GradientDrawable.Orientation.TL_BR;
                    break;
            }
            draw.setOrientation(orientation);
        }
        if (background.circle) {
            if (width > 0 && height > 0) {
                int radius = Math.min(width, height);
                draw.setCornerRadius(radius);
            }
        } else if (background.leftTop > 0 || background.rightTop > 0 || background.leftBottom > 0 || background.rightBottom > 0) {
            float[] radii = new float[]{
                    background.leftTop, background.leftTop,
                    background.rightTop, background.rightTop,
                    background.rightBottom, background.rightBottom,
                    background.leftBottom, background.leftBottom
            };
            draw.setCornerRadii(radii);

        } else if (background.radius > 0) {
            draw.setCornerRadius(background.radius);
        }
        background.drawable = draw;
        View v = mTarget.get();
        if (v != null)
            v.setBackground(background.drawable);
    }

    public void onLayout(int w, int h) {
        this.width = w;
        this.height = h;
        updateBackgroundDrawable();
    }

    /**
     * 给color添加透明度
     *
     * @param alpha 透明度 0f～1f
     * @param color 基本颜色
     */
    public int getColorWithAlpha(float alpha, int color) {
        int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
        int rgb = 0x00ffffff & color;
        return a + rgb;
    }

    public int getDesignScreenWidth() {
        return this.designScreenWidth;
    }

    public float getDesignScale() {
        if (scaleEnabled)
            return this.designScale;
        return 1f;
    }

    public float calDesignScale() {
        Context cxt = getContext();
        if (cxt == null) return 0;
        return AutoUtil.calDesignScale(cxt, getDesignScreenWidth());
    }

    public int calDesignSize(int size) {
        return AutoUtil.calDesignSize(size, getDesignScale());
    }

    public void setDesignScale(float designScale) {
        this.designScale = designScale;
    }

    public boolean isBreakLayout(View child) {
        if (child.getTag() == null) {
            //屏蔽一些特殊View
            if (child instanceof FrameLayout)
                return false;
            if (child instanceof LinearLayout)
                return false;
            if (child instanceof LinearLayoutCompat)
                return false;
            if (child instanceof RelativeLayout)
                return false;
            return true;
        }
        String tag = child.getTag().toString();
        return !TextUtils.equals("auto", tag);
    }

    static class BackgroundStyle {
        public int backgroundColor = Color.TRANSPARENT;
        public boolean circle = false;
        public int radius = 0;
        public int leftTop = 0;
        public int rightTop = 0;
        public int leftBottom = 0;
        public int rightBottom = 0;
        public float alphaStart = 0f;
        public float alphaEnd = 1f;
        public int angle = 0;
        public Drawable drawable = null;
    }
}
